<script setup>
import { ref } from 'vue';

let intervalId;
const utl = "http://127.0.0.1:8888/screen";
const heart = "http://127.0.0.1:8888/api/heart"
const showLoading = ref(true);
const iframeVisible = ref(false);

function checkAndRedirect() {
  fetch(heart).then(response => {
    if (response.ok) {
      // 请求成功，停止轮询，显示iframe
      if (!iframeVisible.value) {
        showLoading.value = false;
        iframeVisible.value = true;
      }
    } else {
      if (iframeVisible.value) {
        showLoading.value = true;
        iframeVisible.value = false;
      }
    }
  }).catch(error => {
    if (iframeVisible.value) {
      showLoading.value = true;
      iframeVisible.value = false;
    }
    console.log("请求失败，继续轮询...", error);
  });
}

// 每隔 3 秒执行一次请求
window.onload = function () {
  checkAndRedirect();
  intervalId = setInterval(checkAndRedirect, 10000);
};
</script>

<template>
  <div class="centered" v-if="showLoading">
    <div class="loading-text">正在连接...</div>
    <div class="spinner">
      <svg width="50" height="50" viewBox="0 0 24 24">
        <circle cx="4" cy="12" r="3" fill="currentColor">
          <animate id="svgSpinners3DotsBounce0" attributeName="cy" begin="0;svgSpinners3DotsBounce1.end+0.25s"
            calcMode="spline" dur="0.6s" keySplines=".33,.66,.66,1;.33,0,.66,.33" values="12;6;12" />
        </circle>
        <circle cx="12" cy="12" r="3" fill="currentColor">
          <animate attributeName="cy" begin="svgSpinners3DotsBounce0.begin+0.1s" calcMode="spline" dur="0.6s"
            keySplines=".33,.66,.66,1;.33,0,.66,.33" values="12;6;12" />
        </circle>
        <circle cx="20" cy="12" r="3" fill="currentColor">
          <animate id="svgSpinners3DotsBounce1" attributeName="cy" begin="svgSpinners3DotsBounce0.begin+0.2s"
            calcMode="spline" dur="0.6s" keySplines=".33,.66,.66,1;.33,0,.66,.33" values="12;6;12" />
        </circle>
      </svg>
    </div>
  </div>
  <!-- 嵌入式网页 -->
  <iframe v-if="iframeVisible" :src="utl" class="embedded-frame" frameborder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
  </iframe>
</template>
<style>
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  font-size: 22px;
}

.loading-text {
  margin-bottom: 30px;
  font-weight: bold;
  letter-spacing: 1px;
  color: #2c7ef8;
}

.spinner svg {
  fill: #fff;
  color: #ffeb3b;
  /* 动画圆点颜色：亮黄 */
}

.embedded-frame {
  width: 100%;
  height: 100vh;
  border: none;
  position: fixed;
  top: 0;
  left: 0;
}
</style>